﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Microsoft.Reporting.WebForms;
using Microsoft.SharePoint;

namespace DynamicSSRSReport.SPListDynamicSSRSReportWithSelectColumnsOption
{
    public partial class SPListDynamicSSRSReportWithSelectColumnsOptionUserControl : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                loadAllLists();
            }
        }

        private void loadAllLists()
        {
            try
            {
                ddlTables.Items.Clear();
                using (SPSite site = new SPSite(SPContext.Current.Web.Url.ToString()))
                {
                    foreach (SPWeb web in site.AllWebs)
                    {
                        foreach (SPList list in web.Lists)
                        {
                            ddlTables.Items.Add(new System.Web.UI.WebControls.ListItem(list.Title.ToString(), list.Title.ToString()));
                        }
                        web.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                lblMsg.Text = "Error : " + ex.Message.ToString() + "     Stack Trace : " + ex.StackTrace.ToString();
            }
        }

        private DataTable ConvertSPListToDataTable(string spListName)
        {
            //SPWeb oWebsite = SPContext.Current.Web;
            //SPList oList = oWebsite.Lists[spListName];
            //SPListItemCollection collListItems = oList.Items;
            //return collListItems.GetDataTable();

            SPWeb web = SPContext.Current.Web;

            // Build a query.
            SPQuery query = new SPQuery();
            query.Query = string.Concat(
                           "<Where><Neq>",
                              "<FieldRef Name='ID'/>",
                              "<Value Type='Counter'>0</Value>",
                           "</Neq></Where>");

            //query.ViewFields = string.Concat(
            //                    "<FieldRef Name='AssignedTo' />",
            //                    "<FieldRef Name='LinkTitle' />",
            //                    "<FieldRef Name='DueDate' />",
            //                    "<FieldRef Name='Priority' />");

            string[] split = GetSelectedColumnsInternalNames().Split(new Char[] { ',' });
            foreach (string s in split)
            {
                query.ViewFields = string.Concat(query.ViewFields, "<FieldRef Name='" + s + "' />");
            }

            query.ViewFieldsOnly = true; // Fetch only the data that we need.

            // Get data from a list.
            SPList oList = web.Lists[spListName];
            SPListItemCollection items = oList.GetItems(query);
            return items.GetDataTable();
        }

        protected void btnShowReport_Click(object sender, EventArgs e)
        {
            try
            {
                #region GetDatatable
                string tName = ddlTables.SelectedItem.Text.ToString();
                string dsName = ddlTables.SelectedValue;
                DataTable dt = ConvertSPListToDataTable(tName);

                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    dt.Columns[i].ColumnName = ReportGenerator.FormatForDynamicRdlc(dt.Columns[i].ColumnName);
                }
                dt.AcceptChanges();

                #endregion

                #region RDLC
                ReportGenerator gen = new ReportGenerator(dt, dsName);
                ReportDataSource ds = new ReportDataSource(dsName, dt);
                ReportViewer1.Reset();
                ReportViewer1.LocalReport.DataSources.Add(ds);
                ReportViewer1.LocalReport.DisplayName = dsName;
                ReportViewer1.LocalReport.LoadReportDefinition(gen.GeneraReport());
                #endregion
            }
            catch (Exception ex)
            {
                lblMsg.Text = "Error : " + ex.Message.ToString() + "     Stack Trace : " + ex.StackTrace.ToString();
            }
        }

        protected void btnShowColumns_Click(object sender, System.EventArgs e)
        {
            try
            {
                string tName = ddlTables.SelectedItem.Text.ToString();
                string dsName = ddlTables.SelectedValue;
                chklstColumns.Items.Clear();
                chklstColumns.Visible = false;

                using (SPSite site = new SPSite(SPContext.Current.Web.Url.ToString()))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList list = web.Lists[tName];
                        //foreach (SPListItem listItem in list.Items)
                        //{
                        foreach (SPField field in list.Fields)
                        {
                            chklstColumns.Items.Add(new System.Web.UI.WebControls.ListItem(field.Title.ToString(), field.InternalName.ToString()));
                            //object value = listItem[field.Id];
                            //System.Diagnostics.Debug.WriteLine(field.Title + ": " + (value == null ? "(null)" : value.ToString()));
                        }
                        //}
                    }
                }

                if (chklstColumns.Items.Count > 0) chklstColumns.Visible = true;
            }
            catch (Exception ex)
            {
                lblMsg.Text = "Error : " + ex.Message.ToString() + "     Stack Trace : " + ex.StackTrace.ToString();
            }
        }

        private string GetSelectedColumnsNames()
        {
            string sColumns = string.Empty;

            for (int i = 0; i < chklstColumns.Items.Count; i++)
            {
                if (chklstColumns.Items[i].Selected == true)
                {
                    sColumns += chklstColumns.Items[i].Text.ToString() + ",";
                }
            }
            sColumns = sColumns.TrimEnd(',');

            return sColumns;
        }

        private string GetSelectedColumnsInternalNames()
        {
            string sColumns = string.Empty;

            for (int i = 0; i < chklstColumns.Items.Count; i++)
            {
                if (chklstColumns.Items[i].Selected == true)
                {
                    sColumns += chklstColumns.Items[i].Value.ToString() + ",";
                }
            }
            sColumns = sColumns.TrimEnd(',');

            return sColumns;
        }

        protected void btnSelectAll_Click(object sender, System.EventArgs e)
        {
            if (btnSelectAll.Text == "SelectAll")
            {
                btnSelectAll.Text = "DeSelectAll";
                foreach (ListItem li in chklstColumns.Items)
                {
                    li.Selected = true;
                }
            }
            else
            {
                btnSelectAll.Text = "SelectAll";
                chklstColumns.ClearSelection();
            }
        }
    }
}
